import React, { Component } from 'react'

export default class CartSample extends Component {
  constructor(){
    super();
    this.state={
      data:[
        {
          id: 1,
          text: '哈哈哈'
        },
        {
          id: 2,
          text: '呵呵呵'
        },
        {
          id: 3,
          text: '嘿嘿嘿'
        },
      ],
      inputValue:'',
      cartData: [],
    }
  }
  inputOnChange(e){
    this.setState({
      inputValue:e.target.value
    })
  }
  addGood=()=>{
    this.setState(prevState => {
      return {
        data:[
          ...prevState.data,
          {
            id: prevState.data.length + 1,
            text: prevState.inputValue 
          }
        ],
        inputValue:'',
      }
    })
  }
  addToCart = good =>{
    const newCart = this.state.cartData;
    const idx = newCart.findIndex(c=> c.id === good.id);
    const item = newCart[idx];
    if(item){
      newCart.splice(idx,1,{...item,count:item.count + 1})
    }else{
      newCart.push({...good,count:1})
    }
    this.setState({cartData: newCart})
  }
  add=(good)=>{
    const newCart = this.state.cartData;
    const idx = newCart.findIndex(c=> c.id === good.id);
    const item = newCart[idx];
    newCart.splice(idx,1,{...item,count:item.count + 1})
    this.setState({cartData: newCart})
  }
  minus=(good)=>{
    const newCart = this.state.cartData;
    const idx = newCart.findIndex(c=> c.id === good.id);
    const item = newCart[idx];
    if(item.count-1 === 0){
      newCart.splice(idx,1)
    }else{
      newCart.splice(idx,1,{...item,count:item.count - 1})
    }
    this.setState({cartData: newCart})
  }
  render() {
    return (
      <div>
        <section>
          <input type="text" value={this.state.inputValue} onChange={(e)=>this.inputOnChange(e)}/>
          <button onClick={this.addGood}>添加</button>
        </section>
        <ul>
          {this.state.data.map((item,index) => (
            <li key={index}>
            {item.text}
            <button onClick={()=>this.addToCart(item)}>添加入购物车</button>
            </li>
          ))}
        </ul>
        <Cart cartData={this.state.cartData} add={this.add} minus={this.minus}/>
      </div>
    )
  }
}
function Cart({cartData,add,minus}){
  return(
    <div>
      {cartData.map((item,index)=>(
        <div key={index}>
          {item.text}
          <button onClick={()=>add(item)}>+</button>
          {item.count}
          <button onClick={()=>minus(item)}>-</button>
        </div>
      ))}
    </div>
 )
}
